package com.ruoyi.common.utils.http;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

public class NetworkCheck {
    public static void main(String[] args) {
        String server = "192.168.1.80";
        if (checkConnect(server)) {
            System.out.println("Connected to " + server);
        } else {
            System.out.println("Not connected to " + server);
        }

        List<String> ips = getIps();
        System.out.println("检查总数：" + ips.size());
        for (int i = 0; i < 8; i++) {
            long start = System.currentTimeMillis();
            Map<String, Boolean> map = bathCheckConnect(ips);
            System.out.println("结果：\n" + map);
            System.out.println("结果总数：" + map.size());
            System.out.println("耗时：" + (System.currentTimeMillis() - start) / 1000D + "秒");
        }
    }

    private static List<String> getIps() {
        List<String> ips = new ArrayList<>();
        ips.add("192.168.1.11");
        ips.add("192.168.1.12");
        ips.add("192.168.1.124");
        ips.add("192.168.1.125");
        ips.add("192.168.1.101");
        ips.add("192.168.1.102");
        ips.add("192.168.1.88");
        ips.add("192.168.1.89");
        ips.add("192.168.1.93");
        ips.add("192.168.1.94");
        ips.add("192.168.1.95");
        ips.add("192.168.1.96");
        ips.add("192.168.1.97");
        ips.add("192.168.1.98");
        ips.add("192.168.1.99");
        ips.add("192.168.1.100");
        ips.add("192.168.1.103");
        ips.add("192.168.1.104");
        return ips;
    }

    public static Map<String, Boolean> bathCheckConnect(List<String> ips) {
        // 创建线程池（根据任务数量动态调整大小）
        int threadCount = Math.min(ips.size(), Runtime.getRuntime().availableProcessors() * 2);
        ExecutorService executor = Executors.newFixedThreadPool(threadCount);

        // 用于存储结果的并发Map
        Map<String, Boolean> resultMap = new ConcurrentHashMap<>();

        // 创建任务列表
        List<Callable<Void>> tasks = new ArrayList<>();
        for (String ip : ips) {
            tasks.add(() -> {
                resultMap.put(ip, checkConnect(ip));
                return null;
            });
        }

        try {
            // 批量执行所有任务并等待完成
            executor.invokeAll(tasks);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.err.println("批量检查被中断: " + e.getMessage());
        } finally {
            // 关闭线程池
            executor.shutdown();
            try {
                // 等待所有任务完成（最多10秒）
                if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
                    executor.shutdownNow();
                }
            } catch (InterruptedException e) {
                executor.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }

        return resultMap;
    }

    public static boolean checkConnect(String server) {
        String[] command;
        if (System.getProperty("os.name").toLowerCase().startsWith("win")) {
            command = new String[]{"ping", "-n", "1", "-w", "1000", server};
        } else {
            command = new String[]{"ping", "-c", "1", "-W", "1", server};
        }

        Process process = null;
        try {
            ProcessBuilder pb = new ProcessBuilder(command);
            pb.redirectErrorStream(true);
            process = pb.start();

            try (InputStream is = process.getInputStream();
                 BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {

                String line;
                while ((line = reader.readLine()) != null) {
                    if (line.toLowerCase().contains("ttl")) {
                        return true;
                    }
                }
            }

            int exitCode = process.waitFor();
            return exitCode == 0;

        } catch (Exception e) {
            System.err.println("Error checking connection to " + server + ": " + e.getMessage());
            return false;
        } finally {
            if (process != null && process.isAlive()) {
                process.destroy();
            }
        }
    }
}
